package com.megvii.koala.tv.presenter;

import android.content.Intent;

import com.megvii.koala.base.KoalaPresenter;
import com.megvii.koala.tv.activity.MainActivity;
import com.megvii.koala.tv.data.ServerManager;
import com.megvii.koala.tv.data.SurveillanceCameraManager;
import com.megvii.koala.tv.data.TVBoxManager;
import com.megvii.koala.tv.data.TVGlobalData;
import com.megvii.koala.tv.fragment.BoxSettingFragment;
import com.megvii.koala.tv.fragment.ServerSettingFragment;
import com.megvii.koala.tv.fragment.param.ServerSettingParam;

/**
 * Created by linyue on 16/1/22.
 */
public class ServerSettingPresenter extends KoalaPresenter<ServerSettingFragment>
        implements ServerSettingFragment.ServerSettingListener
{
    private ServerSettingParam param;

    private ServerManager serverManager;

    private TVBoxManager boxManager;

    private SurveillanceCameraManager cameraManager;

    @Override
    protected void onCreated()
    {
        super.onCreated();
        param = viewHolder.getParam();
        serverManager = TVGlobalData.instance().serverManager;
        boxManager = TVGlobalData.instance().boxManager;
        cameraManager = TVGlobalData.instance().cameraManager;
        viewHolder.setListener(this);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        String address = serverManager.getAddress();
        if (address == null || address.isEmpty())
        {
            //TODO
            address = "http://v2.koalacam.net";
        }
        viewHolder.setServerAddress(address);
        viewHolder.setConfirmButtonText("下一步");
    }

    @Override
    public void onBackPressed()
    {
        if (param.isInit)
        {
            viewHolder.getActivity().finish();
        }
        else
        {
            viewHolder.finish();
        }
    }

    @Override
    public void onClickConfirm()
    {
        boxManager.clearSelection();
        cameraManager.persistentClear();
        serverManager.setAddress(viewHolder.getServerAddress());
        if (param.isInit)
        {
            viewHolder.finish();
            Intent intent = new Intent(viewHolder.getActivity(), MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            viewHolder.startActivity(intent);
        }
        else
        {
            viewHolder.startFragment(BoxSettingFragment.class, null);
        }
    }
}
